function getVehicleHandlingProperty ( element, property )
    if isElement ( element ) and getElementType ( element ) == "vehicle" and type ( property ) == "string" then
        local handlingTable = getVehicleHandling ( element )
        local value = handlingTable[property]
        if value then
            return value
        end
    end
    return false
end

local vehicleEngines = {
    ["1.0"] = {
        vehicleAcceleration = -1;
    };
    ["1.0T"] = {
        vehicleAcceleration = -0.2;
    };
    ["1.1"] = {
        vehicleAcceleration = -0.7;
    };
    ["1.1T"] = {
        vehicleAcceleration = 0.1;
    };
    ["1.2"] = {
        vehicleAcceleration = -0.8;
    };
    ["1.2T"] = {
        vehicleAcceleration = 0;
    };
    ["1.3"] = {
        vehicleAcceleration = -0.4;
    };
    ["1.3T"] = {
        vehicleAcceleration = 0.4;
    };
    ["1.4"] = {
        vehicleAcceleration = -0.6;
    };
    ["1.4T"] = {
        vehicleAcceleration = 0.2;
    };
    ["1.5"] = {
        vehicleAcceleration = -0.1;
    };
    ["1.5T"] = {
        vehicleAcceleration = 0.7;
    };
    ["1.6"] = {
        vehicleAcceleration = -0.4;
    };
    ["1.6T"] = {
        vehicleAcceleration = 0.4;
    };
    ["1.7"] = {
        vehicleAcceleration = 0.2;
    };
    ["1.7T"] = {
        vehicleAcceleration = 1;
    };
    ["1.8"] = {
        vehicleAcceleration = -0.2;
    };
    ["1.8T"] = {
        vehicleAcceleration = 0.6;
    };
    ["1.9"] = {
        vehicleAcceleration = 0.4;
    };
    ["1.9T"] = {
        vehicleAcceleration = 1.3;
    };
    ["2.0"] = {
        vehicleAcceleration = 0;
    };
    ["2.0T"] = {
        vehicleAcceleration = 0.8;
    };
    ["2.1"] = {
        vehicleAcceleration = 0.9;
    };
    ["2.1T"] = {
        vehicleAcceleration = 1.7;
    };
    ["2.2"] = {
        vehicleAcceleration = 0.3;
    };
    ["2.2T"] = {
        vehicleAcceleration = 1.1;
    };
    ["2.3"] = {
        vehicleAcceleration = 1.3;
    };
    ["2.3T"] = {
        vehicleAcceleration = 2.1;
    };
    ["2.4"] = {
        vehicleAcceleration = 0.6;
    };
    ["2.4T"] = {
        vehicleAcceleration = 1.4;
    };
    ["2.5"] = {
        vehicleAcceleration = 1.7;
    };
    ["2.5T"] = {
        vehicleAcceleration = 2.5;
    };
    ["2.6"] = {
        vehicleAcceleration = 0.9;
    };
    ["2.6T"] = {
        vehicleAcceleration = 1.7;
    };
    ["2.7"] = {
        vehicleAcceleration = 2.1;
    };
    ["2.7T"] = {
        vehicleAcceleration = 2.9;
    };
    ["2.8"] = {
        vehicleAcceleration = 1.2;
    };
    ["2.8T"] = {
        vehicleAcceleration = 2.0;
    };
    ["2.9"] = {
        vehicleAcceleration = 2.5;
    };
    ["2.9T"] = {
        vehicleAcceleration = 3.3;
    };
    ["3.0"] = {
        vehicleAcceleration = 1.6;
    };
    ["3.0T"] = {
        vehicleAcceleration = 2.4;
    };
    ["3.1"] = {
        vehicleAcceleration = 3.0;
    };
    ["3.1T"] = {
        vehicleAcceleration = 3.8;
    };
	["3.2"] = {
        vehicleAcceleration = 2.0;
    };
	["3.2T"] = {
        vehicleAcceleration = 2.8;
    };
	["3.3"] = {
        vehicleAcceleration = 3.5;
    };
	["3.3T"] = {
        vehicleAcceleration = 4.3;
    };
	["3.4"] = {
        vehicleAcceleration = 2.4;
    };
	["3.4T"] = {
        vehicleAcceleration = 3.2;
    };
	["3.5"] = {
        vehicleAcceleration = 4.0;
    };
	["3.5T"] = {
        vehicleAcceleration = 4.8;
    };
	["3.6"] = {
        vehicleAcceleration = 2.8;
    };
	["3.6T"] = {
        vehicleAcceleration = 3.6;
    };
	["3.7"] = {
        vehicleAcceleration = 4.5;
    };
	["3.7T"] = {
        vehicleAcceleration = 5.3;
    };
	["3.8"] = {
        vehicleAcceleration = 3.2;
    };
	["3.8T"] = {
        vehicleAcceleration = 4.0;
    };
	["3.9"] = {
        vehicleAcceleration = 5.0;
    };
	["3.9T"] = {
        vehicleAcceleration = 5.8;
    };
	["4.0"] = {
        vehicleAcceleration = 3.7;
    };
	["4.0T"] = {
        vehicleAcceleration = 4.5;
    };
	["4.1"] = {
        vehicleAcceleration = 5.6;
    };
	["4.1T"] = {
        vehicleAcceleration = 6.4;
    };
	["4.2"] = {
        vehicleAcceleration = 4.2;
    };
	["4.2T"] = {
        vehicleAcceleration = 5.0;
    };
	["4.3"] = {
        vehicleAcceleration = 6.2;
    };
	["4.3T"] = {
        vehicleAcceleration = 7.0;
    };
	["4.4"] = {
        vehicleAcceleration = 4.7;
    };
	["4.4T"] = {
        vehicleAcceleration = 5.5;
    };
	["4.5"] = {
        vehicleAcceleration = 6.8;
    };
	["4.5T"] = {
        vehicleAcceleration = 7.6;
    };
	["4.6"] = {
        vehicleAcceleration = 5.2;
    };
	["4.6T"] = {
        vehicleAcceleration = 6.0;
    };
	["4.7"] = {
        vehicleAcceleration = 7.4;
    };
	["4.7T"] = {
        vehicleAcceleration = 8.2;
    };
	["4.8"] = {
        vehicleAcceleration = 5.7;
    };
	["4.8T"] = {
        vehicleAcceleration = 6.5;
    };
	["4.9"] = {
        vehicleAcceleration = 8.0;
    };
	["4.9T"] = {
        vehicleAcceleration = 8.8;
    };
	["5.0"] = {
        vehicleAcceleration = 6.2;
    };
	["5.0T"] = {
        vehicleAcceleration = 7.0;
    };
}

function onRespawnVehicles(id,poss,plr)
    local q = exports["cmta-db"]:dbGet("SELECT * FROM cmta_pojazdy WHERE id=? LIMIT 1", id)
    if q and #q > 0 then
        local d = q[1]
        local pos=split(d.pos, ",")
		if poss then pos={poss[1], poss[2], poss[3], poss[4], poss[5], poss[6]} end
        local vehicle = createVehicle(d.model, pos[1],pos[2],pos[3],pos[4],pos[5],pos[6])

        if d.spoiler ~= 0 then
            local spoiler=split(d.spoilerOffsets, ",")
            local spojler = createObject( d.spoiler, -1745.15491, -137.97495, 3.55469+0.60)
            attachElements ( spojler, vehicle, spoiler[1],spoiler[2],spoiler[3])
            setObjectScale(spojler,(spoiler[4] or 1))
            d.spoiler2 = spojler
        end

        setElementData(vehicle, "vehicle:data", {
            id = d.id,
            fuel = d.fuel,
            mileage = d.mileage,
            driver = nil,
            rent = (split(d.rent, ",") or {}),
            ownedGroup = d.ownedGroup,
            ownedPlayer = d.ownedPlayer,
            driveType = d.driveType,
            engine = d.engine,
            engineType = d.engineType,
            tank = d.tank,
            colorspeedo = d.colorspeedo,
            launchcontrol = d.LaunchControl,
            shader = d.shader,
            mk1 = d.mk1,
            mk2 = d.mk2,
            mk3 = d.mk3,
            asr = d.asr,
            spoiler = (d.spoiler2 or d.spoiler),
            sterringlock = d.sterringLock
        })

        setVehicleHandling(vehicle,"engineAcceleration",getVehicleHandlingProperty(vehicle,"engineAcceleration") + vehicleEngines[d.engine].vehicleAcceleration)
        local color=split(d.color, ",")
        local lights=split(d.headlights, ",")
        setVehicleColor(vehicle, color[1], color[2], color[3], color[4],color[5], color[6], color[7], color[8],color[9], color[10], color[11], color[12])
        setVehicleHeadLightColor(vehicle, lights[1], lights[2], lights[3])
		setElementDimension(vehicle,tonumber(d.dimension))		
        setElementHealth(vehicle, d.health)
        if d.plateText ~= "" then
            setVehiclePlateText(vehicle, d.plateText)
		else
		    setVehiclePlateText(vehicle, tostring(""..d.id))
		end

        local upgrades = split(d.tuning, ",")
        for i, v in ipairs(upgrades) do
            addVehicleUpgrade(vehicle, v)
        end

        for _, upgrade in ipairs ( getVehicleUpgrades ( vehicle ) ) do
			if upgrade == 1025 then
			setVehicleHandling(vehicle, "handlingFlags", 3145729)
			end
		end
        setElementFrozen(vehicle,false)
        if poss then
		warpPedIntoVehicle(plr,vehicle)
        triggerClientEvent(plr, 'createVehicleBlip', getRootElement(), vehicle)
        triggerClientEvent(plr,"cmta_vehicles:clear",plr,vehicle)
        end
        checkUpgrades(vehicle)
        exports["cmta-db"]:dbSet("UPDATE cmta_pojazdy SET parking=0 WHERE id=? LIMIT 1", id)


    end


end


function onSaveVehicle(vehicle,plr)
    if not getElementData(vehicle, "vehicle:data") then
        outputChatBox("Auto które chcesz zapisać nie znajduje się w bazie danych.",plr)
        return false
    end
    local data = getElementData(vehicle, "vehicle:data")
    local health=getElementHealth(vehicle)
    local x,y,z=getElementPosition(vehicle)
    local rx,ry,rz=getElementRotation(vehicle)
    local id=data.id
    local fuel=data.fuel
    local mileage=data.mileage
    local c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12=getVehicleColor(vehicle, true)
    local driver=data.driver or ""
    upgrades=getVehicleUpgrades(vehicle)
    if not upgrades then upgrades={} end
    upgrades=table.concat(upgrades, ",")
    local q = exports["cmta-db"]:dbSet(string.format("UPDATE cmta_pojazdy SET health='%d', pos='%.2f,%.2f,%.2f,%.2f,%.2f,%.2f', fuel='%d', mileage='%d', color='%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d', driver='%s', tuning='%s', dimension='%d' WHERE id=%d",
        health, x,y,z,rx,ry,rz, fuel, mileage, c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12, driver, upgrades, getElementDimension(vehicle), id))
    if q then
        if plr then
            triggerClientEvent(plr, "removeVehicleBlip", getRootElement(), vehicle)
            destroyElement(vehicle)
        end
        return true
    else
        return false
    end
end

function checkUpgrades(vehicle)
    local data = getElementData(vehicle, "vehicle:data")
    if not data then return end
    if tonumber(data.mk1) ~= 0 then
        setVehicleHandling(vehicle,"engineAcceleration",getVehicleHandlingProperty(vehicle,"engineAcceleration") +0.8)
    end
    if tonumber(data.mk2) ~= 0 then
        setVehicleHandling(vehicle,"engineAcceleration",getVehicleHandlingProperty(vehicle,"engineAcceleration") +1)
    end
    if tonumber(data.mk3) ~= 0 then
        setVehicleHandling(vehicle,"engineAcceleration",getVehicleHandlingProperty(vehicle,"engineAcceleration") +1.3)
    end
end


addEventHandler("onResourceStart", getResourceRootElement(), function()
    local q = exports["cmta-db"]:dbGet("SELECT * FROM cmta_pojazdy WHERE parking=0")
    local count = 0
    if q and #q > 0 then
        for i, v in ipairs(q) do
            local x = q[i]
            onRespawnVehicles(x.id)
            count = count+1
        end
    end
    outputDebugString("[CMTA] Pomyślnie załadowano "..count.." pojazdów.",4,102,178,255)
end)

addEventHandler("onResourceStop", getResourceRootElement(), function()
    for i, v in ipairs(getElementsByType("vehicle")) do
        local data = getElementData(v, "vehicle:data")
        if data then
            if getElementHealth(v) < 300 then setElementHealth(v,350) end
            onSaveVehicle(v)
        end
    end
    outputDebugString("[CMTA] Pomyślnie zapisano pojazdy prywatne.",4,102,178,255)
end)

addEventHandler("onVehicleStartEnter", getRootElement(), function(localPlayer, seat, jacked, door)
    if jacked then
        cancelEvent()
    end
end)

addEventHandler("onVehicleEnter", getRootElement(), function(localPlayer)
    local data = getElementData(source, "vehicle:data")
    if not data then return end
    data.driver = getPlayerName(localPlayer)
    setElementData(source, "vehicle:data", data)
end)

--[[
    PRZYDATNE FUNKCJE
--]]

function wybuch (loss)
    local hp = getElementHealth(source) - loss
    if hp <= 315 then
        setVehicleDamageProof(source, true)
        setElementHealth(source, 315)
        setVehicleDamageProof(source, false)
        cancelEvent()
    end
end
addEventHandler("onVehicleDamage", getRootElement(), wybuch)

function tableRemoveValue(t, value)
    for i, v in ipairs(t) do
        if v == value then
            table.remove(t, i)
            return i
        end
    end
    return false
end

function findVehicleByID(id)
    for i, v in ipairs(getElementsByType("vehicle")) do
        local data = getElementData(v, "vehicle:data")
        if data then
            if tonumber(data.id) == tonumber(id) then
                return v
            end
        end
    end
end

function isTrue(value)
    if not value then return false end
    if tonumber(value) == 0 then return false end
    if tonumber(value) == 1 then return true end
    if value == true then return true end
end
